package com.xrit.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.constant.MessageConstant;
import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.service.MemberService;
import com.xrit.sunnyday.service.ReportService;
import com.xrit.sunnyday.service.SetmealService;
import com.xrit.sunnyday.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * 统计报表
 */
@RestController
@RequestMapping("/report")
public class ReportController {

    /**
     * 会员的接口
     */
    @Reference
    private MemberService memberService;

    /**
     * 套餐的接口
     */
    @Reference
    private SetmealService setmealService;

    /**
     * 统计报表接口
     */
    @Reference
    private ReportService reportService;

    /**
     * 会员折线图
     */
    @GetMapping("/getMemberReport")
    public Result getMemberReport() {
        // 准备去年到今年的总共12个月份
        List<String> months = new ArrayList<String>();
        // 使用java中的calendar来操作日期, 日历对象
        Calendar calendar = Calendar.getInstance();
        // 设置过去一年的时间  年-月-日 时:分:秒, 减去12个月
        calendar.add(Calendar.YEAR, -1);
        // 构建12个月的数据
        for (int i = 0; i < 12; i++) {
            try {
                // 每次增加一个月
                calendar.add(Calendar.MONTH, 1);
                // 过去的日期, 设置好的日期
                Date date = calendar.getTime();
                // 转换成我们数据库可以使用的'yyyy-MM-dd'字符串
                String dateString = DateUtils.parseDate2String(date);
                //添加组拼好的过去12个月的月份到List集合
                months.add(dateString);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 准备月份对应的会员数
        List<Integer> memberCount = memberService.getMemberReport(months);
        // 放入map
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("months", months);
        resultMap.put("memberCount", memberCount);
        // 再返回给前端
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, resultMap);
    }

    /**
     * 套餐饼状图
     */
    @GetMapping("/getSetmealReport")
    public Result getSetmealReport() {
        List<Map<String, Object>> list = setmealService.findSetmealCount();
        //放入Map
        Map<String, Object> map = new HashMap();
        map.put("setmealCount", list);
        List<String> setmealNames = new ArrayList<>();
        for (Map<String, Object> m : list) {
            String name = (String) m.get("name");
            setmealNames.add(name);
        }
        map.put("setmealNames", setmealNames);
        return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
    }

    /**
     * 统计分析运营数据
     */
    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        Map<String, Object> mapReport = reportService.getBusinessReportData();
        return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, mapReport);
    }

    /**
     * excel的报表
     */
    @GetMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try {
            Map<String,Object> result = reportService.getBusinessReportData();
            //取出返回结果，准备将报表结果返回给excel
            //日期
            String reportDate = (String) result.get("reportDate");
            //新增会员数(本日)
            int todayNewMember = (int) result.get("todayNewMember");
            //总会员数
            int totalMember = (int) result.get("totalMember");
            //本周新增会员数
            int thisWeekNewMember = (int) result.get("thisWeekNewMember");
            //本月新增会员数
            int thisMonthNewMember = (int) result.get("thisMonthNewMember");
            //今日预约数
            int todayOrderNumber = (int) result.get("todayOrderNumber");
            //今日到诊数
            int todayVisitsNumber = (int) result.get("todayVisitsNumber");
            //本周预约数
            int thisWeekOrderNumber = (int) result.get("thisWeekOrderNumber");
            //本周到诊数
            int thisWeekVisitsNumber = (int) result.get("thisWeekVisitsNumber");
            //本月预约数
            int thisMonthOrderNumber = (int) result.get("thisMonthOrderNumber");
            //本月到诊数
            int thisMonthVisitsNumber = (int) result.get("thisMonthVisitsNumber");
            //热门套餐
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            //获取项目里excel模板的路径
            String filePath = request.getSession().getServletContext().getRealPath("template")+File.separator+"report_template.xlsx";
            //基于提供的Excel模板文件在内存中创建一个Excel表格对象
            //XSSFWorkbook：一般用于操作Excel2007及以上的版本，扩展名是.xlsx
            //FileInputStream即文件字节操作流。即以字节的形式操作文件系统的数据文件。
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));

            //读取第一个工作表
            XSSFSheet sheet = excel.getSheetAt(0);

            //行
            XSSFRow row = sheet.getRow(2);
            //列
            //日期
            row.getCell(5).setCellValue(reportDate);

            row = sheet.getRow(4);
            //新增会员数(本日)
            row.getCell(5).setCellValue(todayNewMember);
            //总会员数
            row.getCell(7).setCellValue(totalMember);

            row = sheet.getRow(5);
            //本周新增会员数
            row.getCell(5).setCellValue(thisWeekNewMember);
            //本月新增会员
            row.getCell(7).setCellValue(thisMonthNewMember);

            row = sheet.getRow(7);
            //今日预约数
            row.getCell(5).setCellValue(todayOrderNumber);
            //今日到诊数
            row.getCell(7).setCellValue(todayVisitsNumber);

            row = sheet.getRow(8);
            //本周预约数
            row.getCell(5).setCellValue(thisWeekOrderNumber);
            //本周到诊数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);

            row = sheet.getRow(9);
            //本月预约数
            row.getCell(5).setCellValue(thisMonthOrderNumber);
            //本月到诊数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);


            //热门套餐
            int lin = 12;
            for (Map map : hotSetmeal) {
                //套餐名称
                String name = (String) map.get("name");
                //预约数量
                Long setmeal_count = (Long) map.get("setmeal_count");
                //占比
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                //备注
                String remark = (String) map.get("remark");
                //执行遍历
                row = sheet.getRow(lin++);
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmeal_count);
                row.getCell(6).setCellValue(proportion.doubleValue());
                row.getCell(7).setCellValue(remark);
            }
            //使用输出流进行表格下载,基于浏览器作为客户端下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型

            String ling = "运营统计数据报表.xlsx";
            //解决下载文件中文乱码问题
            ling = new String(ling.getBytes(),"ISO-8859-1");
            response.setHeader("content-Disposition", "attachment;filename="+ling);//指定以附件形式进行下载
            excel.write(out);
            out.flush();
            out.close();
            excel.close();
            return null;
        } catch (IOException e) {
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
}